package com.zzyl.chinamobileai.config;

import com.zzyl.chinamobileai.Tool.MyTool;
import com.zzyl.chinamobileai.constents.Prompt;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.MessageChatMemoryAdvisor;
import org.springframework.ai.chat.client.advisor.SimpleLoggerAdvisor;
import org.springframework.ai.chat.client.advisor.vectorstore.QuestionAnswerAdvisor;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.ollama.OllamaChatModel;
import org.springframework.ai.openai.OpenAiChatModel;
import org.springframework.ai.openai.OpenAiEmbeddingModel;
import org.springframework.ai.vectorstore.SearchRequest;
import org.springframework.ai.vectorstore.SimpleVectorStore;
import org.springframework.ai.vectorstore.VectorStore;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

@Configuration
public class CommonConfig {

    @Bean
    public ChatClient chatClient(OpenAiChatModel chatModel,
                                 ChatMemory chatMemory,
                                 MyTool myTool,
                                 VectorStore vectorStore){
        return ChatClient.builder(chatModel)
                //给他一个背景身份
                .defaultSystem(Prompt.PROMPT)
                //记录日志的advisor
                    .defaultAdvisors(new SimpleLoggerAdvisor())
                .defaultAdvisors(MessageChatMemoryAdvisor.builder(chatMemory).build())
                .defaultTools(myTool)
                .defaultAdvisors(
                        MessageChatMemoryAdvisor.builder(chatMemory).build(), // CHAT MEMORY
                        new SimpleLoggerAdvisor(),
                        QuestionAnswerAdvisor.builder(vectorStore)
                                .searchRequest(SearchRequest.builder() // 向量检索的请求参数
                                        .similarityThreshold(0.3d) // 相似度阈值
                                        .topK(1) // 返回的文档片段数量
                                        .build())
                                .build()
                )
                .build();
    }

    /**
     * 注入向量数据库
     * @param embeddingModel
     * @return
     */
    @Bean
    public VectorStore vectorStore(OpenAiEmbeddingModel embeddingModel) {
        return SimpleVectorStore.builder(embeddingModel).build();
    }



}
